package com.leyou.trade.web;

import com.leyou.common.exceptios.LyException;
import com.leyou.trade.entity.Order;
import com.leyou.trade.service.OrderService;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.Map;

/**
 * @author 虎哥
 */
@RestController
@RequestMapping("pay")
public class PayController {

    private final OrderService orderService;

    public PayController(OrderService orderService) {
        this.orderService = orderService;
    }

    /**
     * 获取支付链接
     *
     * @param orderId 订单编号
     * @return 支付链接
     */
    @GetMapping("/url/{id}")
    public ResponseEntity<String> getPayUrl(@PathVariable("id") Long orderId) {
        return ResponseEntity.ok(orderService.getPayUrl(orderId));
    }

    /**
     * 微信支付回调通知
     * @param data
     * @return
     */
    @PostMapping(value = "/wx/notify", produces = MediaType.APPLICATION_XML_VALUE)
    public ResponseEntity<Map<String, String>> handleWxNotify(@RequestBody Map<String, String> data){
        // 处理回调
        orderService.handleWxNotify(data);
        // 返回结果
        Map<String, String> msg = new HashMap<>();
        msg.put("return_code", "SUCCESS");
        msg.put("return_msg", "OK");
        return ResponseEntity.ok(msg);
    }

    @GetMapping("/state/{id}")
    public ResponseEntity<Integer> queryOrderState(@PathVariable("id") Long orderId){
        Order order = orderService.getById(orderId);
        if(order == null){
            throw new LyException(400, "订单不存在");
        }
        return ResponseEntity.ok(order.getStatus().getValue());
    }
}
